package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WeCatService;
import com.zzyl.utils.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Slf4j
@Service
public class WeCatServiceImpl implements WeCatService {
    @Override
    public String getPhone(String phoneCode) {
        String access_token = getAccessToken();
        String url="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+access_token;
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code",phoneCode);
        // 将map转换为json字符串
        String JsonStr = JSONUtil.toJsonStr(hashMap);
        // 发送请求
        String result = HttpUtil.post(url, JsonStr);
        // 将json字符串转换为json对象
        JSONObject entries = JSONUtil.parseObj(result);
        // 判断是否正常
        if (entries.getInt("errcode")!=0){
//            正常情况下，没有errcode
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        // 获取用户手机号信息
        String phoneInfoJson = entries.getStr("phone_info");
        // 将json字符串转换为json对象
        JSONObject phoneNumber = JSONUtil.parseObj(phoneInfoJson);
        String phoneNumberStr = phoneNumber.getStr("phoneNumber");
        return phoneNumberStr;

    }




    @Override
    public String getOpenId(String code) {

        // 创建请求对象
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("appid","wxbb011a64d853c3d9");
        hashMap.put("secret","cda676799b38d07b5ebcad578951606e");
        hashMap.put("js_code",code);
        hashMap.put("grant_type", "authorization_code");
        String result = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", hashMap);
        JSONObject entries = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(entries.getStr("errcode"))){
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        return entries.getStr("openid");
    }

    public String getAccessToken() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("appid","wxbb011a64d853c3d9");
        hashMap.put("secret","cda676799b38d07b5ebcad578951606e");
        hashMap.put("grant_type", "client_credential");
        String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", hashMap);
        JSONObject entries = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(entries.getStr("errcode"))){

            throw new RuntimeException(entries.getStr("errmsg"));
        }
        return entries.getStr("access_token");
    }
}
